package net.spider.bttiantang;

import java.io.File;
import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.viva.api.HTTPUtils;

public class Picture {

    // private String fileSavePath = "/imdb/";
    private String             deepStr = "10";
    public final static String imdbUrl = "http://www.imdb.com/";

    /**
     * 
     * @param url
     *            http://www.imdb.com/title/tt1781922/
     * @param long1
     * @throws ClientProtocolException
     * @throws IOException
     * @throws InterruptedException
     */
    public void getFromUrl(String filedir, String url, Long long1) throws ClientProtocolException, IOException, InterruptedException {
        String[] split = url.split("/");
        String imdb = split[split.length - 1];
        String fileName = filedir + File.separator + imdb + "-" + long1;
        String string = HTTPUtils.doGet(url);
        String src = Jsoup.parse(string).select("#title-overview-widget-layout > tbody > tr > #img_primary > div > a > img").attr("src");
        String suffix = src.substring(src.lastIndexOf("."), src.length());
        HTTPUtils.downFile(src, fileName + "sm" + suffix);
//        String link = imdbUrl + Jsoup.parse(string).select("#title-overview-widget-layout > tbody > tr > #img_primary > div > a").attr("href");
//
//        System.out.println("link: " + link);
//        getOneImgFromPage(link, 1, -1, fileName);
    }

    private void getOneImgFromPage(String url, int i, int deep, String fileName) throws ClientProtocolException, IOException, InterruptedException {
        String picContentStr = HTTPUtils.doGet(url);
        Document picPageDoc = Jsoup.parse(picContentStr);
        if (deep <= 0) {
            String countLabel = picPageDoc.select("div#controls.leftright > div#left > span#count-info").text();
            deep = Integer.parseInt(countLabel.split("of")[1].trim());
        }
        if (!deepStr.equals("max")) {
            if (Integer.parseInt(deepStr) < deep) {
                deep = Integer.parseInt(deepStr);

            }
        }
        if (i >= deep) {
            return;
        }
        String src = picPageDoc.select("div #photo-container > #canvas > div.photo > a.cursor-default > img#primary-img").attr("src");
        String suffix = src.substring(src.lastIndexOf("."), src.length());
        HTTPUtils.downFile(src, fileName + "-big-" + i + suffix);
        // Thread.sleep(MyNumberUtil.getRandom(3, 1) * 1000);
        String nextLink = imdbUrl + picPageDoc.select("div#controls.leftright > div#right > a.media-single-next.btn.secondary.small").attr("href");
        getOneImgFromPage(nextLink, ++i, deep, fileName);
    }
}